/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { getConfiguration, levelMap, setCategoriesLevel, WatchEvent } from '@ohos/hvigor';
import { ProjectConfig, writeWatchCache } from '@ohos/hvigor-arkts-compose';
import log4js, { levels } from 'log4js';
import path from 'path';
import { parentPort } from 'worker_threads';

import { ArkPackConst } from '../../const/common-const.js';
import { AbilityTypeEnum } from '../../enum/ability-type-enum.js';
import { HvigorLoggerConfig } from '@ohos/hvigor-logger';

/**
 * 设置环境变量，供loader使用，后续等loader适配完成可删除
 *
 * @param config 编译参数
 */
export const generateLoaderEnv = (config: ProjectConfig) => {
  const env = {
    runtimeOS: config.runtimeOS,
    sdkInfo: config.sdkInfo,
    watchMode: config.watchMode,
    isPreview: config.isPreview ? 'true' : undefined,
    aceManifestPath: config.aceManifestPath,
    appResource: config.appResource,
    rawFileResource: config.rawFileResource,
    aceModuleBuild: config.aceModuleBuild,
    aceModuleRoot: config.aceModuleRoot,
    cachePath: config.cachePath,
    aceProfilePath: config.aceProfilePath,
    aceModuleJsonPath: config.aceModuleJsonPath,
    aceSuperVisualPath: config.aceSuperVisualPath,
    aceBuildJson: config.aceBuildJson,
    compileTool: ArkPackConst.COMPILE_TOOL,
    abilityType: config.abilityType,
    aceCompileMode: config.abilityType === AbilityTypeEnum.WORKER ? AbilityTypeEnum.WORKER : config.aceCompileMode,
    externalApiPaths: config.externalApiPaths.join(path.delimiter),
    enableDebugLine: config.debugLine,
    isFaMode: config.isFaMode ? 'true' : undefined,
    isFirstBuild: config?.collectImportersConfig?.isReload ? 'false' : 'true',
    widgetCompile: config.widgetCompile,
  };
  process.env = { ...process.env, ...env };
  process.env.path = process.env.Path;
};

export function setLogLevel(level: string) {
  setCategoriesLevel(levelMap.get(level) ?? levels.INFO);
  HvigorLoggerConfig.setCategoriesLevel(levelMap.get(level) ?? levels.INFO);
  log4js.shutdown();
  log4js.configure(getConfiguration());
}

export function onTerminateWorker() {
  let pkgName2SourceRoots: Record<string, string[]> = {};
  parentPort!.on('message', async (event) => {
    if (event?.type === WatchEvent.TERMINATE_WORKER) {
      await writeWatchCache(pkgName2SourceRoots);
      parentPort!.postMessage(event);
    }
  });
  return {
    updatePkgName2SourceRoots(data: Record<string, string[]>) {
      pkgName2SourceRoots = data;
    },
  };
}
